package com.dora.gulimall.product.service.impl;

import com.dora.gulimall.product.service.CategoryBrandRelationService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dora.common.utils.PageUtils;
import com.dora.common.utils.Query;

import com.dora.gulimall.product.dao.CategoryDao;
import com.dora.gulimall.product.entity.CategoryEntity;
import com.dora.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> categoryAllList = baseMapper.selectList(null);
        //2、组装成父子的树形结构

        //2.1、先找出一级分类，然后递归找到所有子菜单，封装到一级分类中（在实体类中加一个属性-）
        List<CategoryEntity> collect = categoryAllList.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).sorted((cate1, cate2) -> {
            return (cate1.getSort() == null ? 0 : cate1.getSort()) - (cate2.getSort() == null ? 0 : cate2.getSort());
        }).map((menu) -> {
            menu.setChildren(getChildren(menu, categoryAllList));
            return menu;
        }).collect(Collectors.toList());


        return collect;
    }

    @Override
    public void removeMenusByIds(List<Long> list) {

        //逻辑删除
        baseMapper.deleteByIds(list);
    }

    //[2,25,225]的格式，[父父节点，父节点，节点]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths= new ArrayList<>();
//        List<Long> parentPath=new ArrayList<>();
        findParentPath(catelogId,paths);
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    //[225,25,2]    增加一个递归方法搜索父节点的id并添加到list中
    private void findParentPath(Long catelogId,List<Long> paths){
        //1.查出当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId!=null&&byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return;

    }

    private List<CategoryEntity> getChildren(CategoryEntity father, List<CategoryEntity> all) {
        return all.stream().filter(categoryEntity -> categoryEntity.getParentCid()==father.getCatId())
                .map(categoryEntity ->{categoryEntity.setChildren(getChildren(categoryEntity, all));return categoryEntity;})
                //这里使用使用 comparingInt 方法来比较 int 值，避免自动装箱和拆箱的开销。并且对属性做空判断
                .sorted(Comparator.comparingInt(cate-> cate.getSort()==null?0:cate.getSort()))
                .collect(Collectors.toList());


    }

}